package connections;

import java.util.HashMap;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.util.ajax.Continuation;

import webService.CreateAccountServlet;
import webService.isClientExistServlet;

/**
 * create and register servlets for jetty server in port 12345 
 * @author ran,barak
 *
 */
public class JettyManager implements Runnable{
	private Server server;
	private Context root;
	private SuspendServlet servlet;
	private AcceptSharedFolder acceptSharedFolder;
	private isClientExistServlet isClientExistServlet;
	private CreateAccountServlet createAccountServlet;
	private HashMap <Long, Continuation> hash;
	/**
	 * start the server
	 */
	@Override
	public void run() {
		hash = new HashMap<Long, Continuation>();
		server = new Server(12345);
		// define the root
		root = new Context(server,"/",Context.SESSIONS);
		servlet = new SuspendServlet(this);
		// create the servlets
		acceptSharedFolder = new AcceptSharedFolder();
		isClientExistServlet = new isClientExistServlet();
		createAccountServlet = new CreateAccountServlet();
		// add the servlet to the server
		root.addServlet(new ServletHolder(servlet), "/*");
		root.addServlet(new ServletHolder(acceptSharedFolder), "/AcceptSharedFolder");
		root.addServlet(new ServletHolder(isClientExistServlet), "/isClientExistServlet");
		root.addServlet(new ServletHolder(createAccountServlet), "/CreateAccountServlet");
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * add user connection to the hash
	 * @param computerId computer id 
	 * @param con the continuation
	 */
	public void addUserCon(Long computerId, Continuation con){
		hash.put(computerId, con);
	}

	/**
	 * resume the continuation of this computer
	 * @param computerId the computer id
	 */
	public void resumeComp(Long computerId) {
		// get the continuation
		Continuation cont = hash.remove(computerId);
		if(cont!=null)
			cont.resume();
	}

	/**
	 * remove continuation from the hash
	 * @param computerId the computer id
	 */
	public void removeComp(long computerId) {
		hash.remove(computerId);
		
	}
}
